//Copyright The ZHIYUNCo.All rights reserved.
//Created by admin at2021/8/2.

package api

import (
	"alarm_service/common/client_conn"
	"alarm_service/internal/dto"
	"alarm_service/internal/usecase/command"
	"github.com/gin-gonic/gin"
)

const (
	success          = 200
	unkonwDeviceErr  = 10001 // 设备不存在
	setCommandErr    = 10002 // 下发指令失败
	paramsErr        = 10003 // 参数错误
	offlineDeviceErr = 10004 // 设备不在线
)

type CommandApi struct {
	commandCase *command.CommandCase
}

func NewCommandApi(commandcase *command.CommandCase) *CommandApi {
	return &CommandApi{
		commandCase: commandcase,
	}
}

func (a *CommandApi) OnSetPhoneHandler(c *gin.Context) {
	var req dto.PhoneReq
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, gin.H{"code": paramsErr})
		return
	}
	if len(req.Phones) > 3 {
		c.JSON(200, gin.H{"code": paramsErr})
		return
	}
	for _, phone := range req.Phones {
		if len(phone) != 11 {
			c.JSON(200, gin.H{"code": paramsErr})
			return
		}
	}
	conn := client_conn.GetConn(req.DeviceID)
	if conn == nil {
		c.JSON(200, gin.H{"code": offlineDeviceErr})
		return
	}
	a.commandCase.SetPhone(req, conn)
	c.JSON(200, gin.H{
		"code": success,
	})
}

func (a *CommandApi) OnSetMessageSwitchHandler(c *gin.Context) {
	var req dto.MessageSwitchReq
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, gin.H{"code": paramsErr})
		return
	}
	conn := client_conn.GetConn(req.DeviceID)
	if conn == nil {
		c.JSON(200, gin.H{"code": offlineDeviceErr})
		return
	}
	a.commandCase.SetMessageSwitch(req, conn)
	c.JSON(200, gin.H{
		"code": success,
	})
}

func (a *CommandApi) OnSetRecoverHandler(c *gin.Context) {
	var req dto.RecoverReq
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, gin.H{"code": paramsErr})
		return
	}
	conn := client_conn.GetConn(req.DeviceID)
	if conn == nil {
		c.JSON(200, gin.H{"code": offlineDeviceErr})
		return
	}
	a.commandCase.SetRecover(req, conn)
	c.JSON(200, gin.H{
		"code": success,
	})
}

//func (a *CommandApi) OnGetICCIDHandler(c *gin.Context) {
//	var req dto.ICCIDReq
//	if err := c.ShouldBindJSON(&req); err != nil {
//		c.JSON(200, gin.H{"code": paramsErr})
//		return
//	}
//	conn := client_conn.GetConn(req.DeviceID)
//	if conn == nil {
//		c.JSON(200, gin.H{"code": offlineDeviceErr})
//		return
//	}
//	a.commandCase.SetMessageSwitch(req, conn)
//	c.JSON(200, gin.H{
//		"code": success,
//	})
//}

func (a *CommandApi) OnSetPhoneSwitchHandler(c *gin.Context) {
	var req dto.PhoneSwitchReq
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, gin.H{"code": paramsErr})
		return
	}
	conn := client_conn.GetConn(req.DeviceID)
	if conn == nil {
		c.JSON(200, gin.H{"code": offlineDeviceErr})
		return
	}
	a.commandCase.SetPhoneSwitch(req, conn)
	c.JSON(200, gin.H{
		"code": success,
	})
}
